from django.http import HttpResponse, JsonResponse
from django.views import View


# Create your views here.

# 请求 接收路由中的uuid
# 业务逻辑 生成图片验证码和图片二进制.通过redis把图片验证码保存起来
# 响应 返回图片二进制
class ImageCodeView(View):

    def get(self, request, uuid):
        # 1.接收路由中的uuid
        # 2.生成图片验证码和图片二进制
        from libs.captcha.captcha import captcha
        text, image = captcha.generate_captcha()
        print(text)
        # 3.通过redis把图片验证码保存起来
        from django_redis import get_redis_connection
        redis_cli = get_redis_connection('code')
        redis_cli.setex(uuid, 300, text)
        # 4.返回图片二进制
        return HttpResponse(image, content_type='image/jpg')


# 请求 接收路由中的手机号,图片验证码和查询字符串中的UUID
# 业务逻辑 验证图片验证码,生成短信验证码,保存短信验证码到,发送短信验证码
# 响应 返回响应
# http://127.0.0.1:8000/sms_codes/13339492209/?image_code=pryi&image_code_id=27e66eec-20b2-49aa-8856-caa43202acf7
class SmsCodeView(View):

    def get(self, request, mobile):
        # 1.接收路由中的手机号,图片验证码和查询字符串中的UUID
        image_code = request.GET.get('image_code')
        uuid = request.GET.get('image_code_id')
        # 2.验证参数
        if not all([image_code, uuid]):
            return JsonResponse({'code': '400', 'errmsg': '参数不全'})
        # 3.验证图片验证码
        from django_redis import get_redis_connection
        redis_cli = get_redis_connection('code')
        redis_image_code = redis_cli.get(uuid)
        if redis_image_code is None:
            return JsonResponse({'code': '400', 'errmsg': '图片验证码已过期'})
        if redis_image_code.decode().lower() != image_code.lower():
            return JsonResponse({'code': '400', 'errmsg': '图片验证码错误'})
        # 3.5.判断是否在60s内重复发送短信
        if redis_cli.get('sms_%s' % mobile) is not None:
            return JsonResponse({'code': '400', 'errmsg': '发送短信过于频繁'})
        # 4.生成短信验证码
        from random import randint
        sms_code = '%04d' % randint(0, 9999)
        # 5.保存短信验证码到redis
        pipe = redis_cli.pipeline()
        pipe.setex(mobile, 300, sms_code)
        pipe.setex('sms_%s' % mobile, 60, 1)
        pipe.execute()
        # 6.发送短信验证码
        # from libs.yuntongxun.sms import CCP
        # CCP().send_template_sms(mobile, [sms_code, 5], 1)
        #使用celery发送短信验证码
        from celery_tasks.sms.tasks import celery_send_sms_code
        celery_send_sms_code.delay(mobile, sms_code)
        # 7.响应
        return JsonResponse({'code': '200', 'errmsg': '发送成功'})
